package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseApplyIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.*;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseFileService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 采购申请Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.pr
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/purchaseApply")
public class PurchaseApplyController {

    private static final Log logger = LogFactory.getLog(PurchaseApplyController.class);

    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;


    @Autowired
    private IPurchaseFileService iPurchaseFileService;


    @Autowired
    private IPurchaseDetailService iPurchaseDetailService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_purchaseApply_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/purchaseApply/purchaseApplyList";
    }

    /**
     * 获取采购申请集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_purchaseApply_find")
    @RequestMapping(value = "/purchaseApplyList.do")
    public void purchaseApplyList(HttpServletResponse response, PurchaseApplyIn in) {
        try {
            logger.info("加载采购申请数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<PurchaseApply>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<PurchaseApply> ewPurchaseApply = new EntityWrapper<PurchaseApply>();
            ewPurchaseApply.setEntity(new PurchaseApply());
            //根据采购清单名称查询(根据采购清单ID)
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewPurchaseApply.like("p1.prName", in.getPrName());
            }
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewPurchaseApply.like("co.coNumber", in.getCoNumber());
            }
            //根据请购时间查询
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getEndDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStartDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getStartDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getEndDate(), in.getEndDate() + " " + "23:59:59");
            }
            //根据合同名称查询
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewPurchaseApply.like("co.coName", in.getCoName());
            }
            //根据上报状态
            if (StringUtils.isNotEmpty(in.getReportState())) {
                ewPurchaseApply.like("pur.reportState", in.getReportState());
            }
            //根据请购类别
            if (StringUtils.isNotEmpty(in.getPurType())) {
                ewPurchaseApply.like("pur.purType", in.getPurType());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewPurchaseApply = UserUtils.setEntityWrapper(ewPurchaseApply, "co1", "off1", "p1");
            }
            ewPurchaseApply.orderBy("createDate", false);
            Page<Map<String, Object>> purchaseApplyPage = iPurchaseApplyService.getMapsListPage(page, ewPurchaseApply);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (purchaseApplyPage.getRecords().size() > 0) {
                for (Map<String, Object> purchaseApply : purchaseApplyPage.getRecords()) {
                    JSONObject object = new JSONObject(purchaseApply);
                    object.put("purId", purchaseApply.get("purId"));
                    object.put("createDate",simpleDateFormat.format(purchaseApply.get("createDate")));
                    if(purchaseApply.get("project")!= null){
                        object.put("prName",((Project) purchaseApply.get("project")).getPrName());
                    }
                    if(purchaseApply.get("contract")!= null){
                        object.put("coName",((Contract) purchaseApply.get("contract")).getCoName());
                    }
                    if(purchaseApply.get("contract")!= null){
                        object.put("coNumber",((Contract) purchaseApply.get("contract")).getCoNumber());
                    }
                    if(purchaseApply.get("contractDetail")!= null){
                        object.put("cdId",((ContractDetail) purchaseApply.get("contractDetail")).getCdId());
                    }
                    if(purchaseApply.get("purchaseFile")!= null){
                        object.put("pfId",((PurchaseFile) purchaseApply.get("purchaseFile")).getPfId());
                    }
                    if(purchaseApply.get("contract")!= null){
                        object.put("coCode",((Contract) purchaseApply.get("contract")).getCoCode());
                    }
                    array.put(object);
                }
            }
            json.put("total", purchaseApplyPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载采购申请数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载采购申请数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 更新或者修改
     * @param purchaseApply
     * @param response
     * @param commonFile
     */
    @RequiresPermissions("rules:st_purchaseApply_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(PurchaseApply purchaseApply,CommonFile commonFile,String fileName,String pfId, HttpServletResponse response) {
        try {
            logger.info("保存采购申请-->>开始");
            //获取当前用户id
            String userId = UserUtils.getCurrentUser().getUsId();
            //获取当前用户所属公司
            String finalCompCode = UserUtils.getServerSessionUser().getFinalCompCode();
            iPurchaseApplyService.savePurchaseApply(purchaseApply,commonFile,fileName,pfId,userId,finalCompCode);
            response.getWriter().write(JsonUtil_Org.returnTrue("保存采购申请成功"));
            logger.info("保存采购申请-->结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("保存采购申请-->>Exception" + e.getMessage());
        }
    }


    /**
     * 采购申请详情
     *
     * @param purchaseApplyIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_purchaseApply_view")
    @RequestMapping("/purchaseApplyDesc.do")
    public String purchaseApplyDesc(PurchaseApplyIn purchaseApplyIn, HttpServletRequest request) {
        try {
            logger.info("采购申请详情-->>开始");
            Map<String, Object> purchaseFile = null;
            //注入此请购申请的清单列表信息
            EntityWrapper<PurchaseDetail> ewPurchaseDetail = new EntityWrapper<>();
            ewPurchaseDetail.setEntity(new PurchaseDetail());
            ewPurchaseDetail.eq("pur.purId", purchaseApplyIn.getPurId());
            List<Map<String, Object>> purchaseDetails = iPurchaseDetailService.getPurchaseDetailMaps(ewPurchaseDetail);
            request.setAttribute("purchaseDetailList", JsonUtil.Json2All(purchaseDetails));
            Map<String, Object> purchaseApply = iPurchaseApplyService.getMapById(purchaseApplyIn.getPurId());
            if(null!=purchaseApplyIn.getPfId()){
                // 附件上传详情
                purchaseFile = iPurchaseFileService.getMapById(purchaseApplyIn.getPfId());
            }
            String purDate = simpleDateFormat.format(purchaseApply.get("purDate"));
            purchaseApply.put("purDate",purDate);
            if (purchaseApply.get("createBy") != null) {
                purchaseApply.put("createBy", UserMapManager.getUserLoginNameInMap(purchaseApply.get("createBy").toString()));
            }
            if (purchaseApply.get("updateBy") != null) {
                purchaseApply.put("updateBy", UserMapManager.getUserLoginNameInMap(purchaseApply.get("updateBy").toString()));
            }
            request.setAttribute("purchaseApply", purchaseApply);
            request.setAttribute("purchaseFile", purchaseFile);
            logger.info("采购申请详情-->>结束");
        } catch (Exception e) {
            logger.debug("采购申请详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/purchaseApply/purchaseApplyDesc";
    }


    /**
     * 删除采购清单
     *
     * @param
     * @param response
     */
    @RequiresPermissions("rules:st_purchaseApply_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String purId, HttpServletResponse response) {
        try {
            logger.info("删除采购清单-->>开始");
            iPurchaseApplyService.delPurchaseByPurId(purId);
            logger.info("删除采购清单-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("采购清单删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除采购清单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 修改上报状态
     * @return
     */
    @RequestMapping("/changsReportState.do")
    public void changsReportState(String purId, String checkState, HttpServletResponse response){
        try {
            logger.info("修改上报状态-->>开始");
            //1. 修改上报状态2 已上报
            PurchaseApply purchaseApply = iPurchaseApplyService.selectById(purId);
            purchaseApply.setReportState("2");

            //2. 判定驳回采购申请，则修改审核状态为1 审核中
            if("3".equals(checkState)){
                purchaseApply.setCheckState("1");
            }
            purchaseApply.setPurDate(new Date());
            iPurchaseApplyService.updateById(purchaseApply);
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("采购清单上报成功"));
        }catch (Exception e){
            e.printStackTrace();
            logger.info("修改上报状态-->>结束");
        }
    }

    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toPurchaseApply.do")
    public ModelAndView toAddActivity(String purId,PurchaseFile purchaseFile, HttpServletRequest request) {
        logger.info("添加修改采购申请跳转-->>开始");
        Map<String,Object> purchaseApply = null;
        if(StringUtils.isNotEmpty(purId)) {
            EntityWrapper<PurchaseDetail> purDelEw = new EntityWrapper<>();
            purDelEw.setEntity(new PurchaseDetail());
            purDelEw.eq("purd.purId", purId);
            List<Map<String, Object>> purchaseDetailList = iPurchaseDetailService.getPurchaseDetailMaps(purDelEw);
            purchaseApply = iPurchaseApplyService.getMapById(purId);
            String json2All = JsonUtil.Json2All(purchaseDetailList);
            //合同外改合同内的修改条件
            if("[]".equals(json2All)){
                request.setAttribute("purchaseDetailList", false);
            }else{
                request.setAttribute("purchaseDetailList", true);
            }
            request.setAttribute("purchaseApply", purchaseApply);
        }else{
            Integer companyId = UserUtils.getCurrentUser().getCompanyId();
            request.setAttribute("companyId",companyId);
        }
        logger.info("添加修改采购申请跳转-->>开始");
        return new ModelAndView("st/purchaseApply/purchaseApplyOption");
    }

}
